import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PreOrderTraversal {
    public List<Integer> preOrderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        TreeNode top = null;
        //如果是根节点空 就直接返回
        if (root == null) {
            return list;
        }
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            top = stack.pop();
            cur = top.right;
        }
        return list;
    }

}
